//
//  RegistViewController.m
//  MooreDoll
//
//  Created by Joe on 2014/11/24.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "RegistViewController.h"

@interface RegistViewController ()
{
    AFHTTPRequestOperationManager *afManager;
}
@property (weak, nonatomic) UITextField *TF_ActiveField;

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    //重SIM卡內取得國家 並且顯示國家
    self.LB_CountryCode.text = [TelephonyInfo getCountryCodeString];
    //取得國家代碼 ex:886
    self.ISO_Country_Code =[TelephonyInfo getCountryCodeNumber];

    //左側按鈕
    [self leftBarButton];
}

-(void)leftBarButton
{
    //顯示navigationBar
    self.navigationController.navigationBarHidden = NO;
    
    //創建button
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [leftButton setImage:[UIImage imageNamed:@"top_back"] forState:UIControlStateNormal];
    [leftButton setFrame:CGRectMake(0, 0, [UIImage imageNamed:@"top_back"].size.width, [UIImage imageNamed:@"top_back"].size.height)];
    //button 返回事件
    [leftButton addTarget:self action:@selector(goBackToSourceVC:)forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem = leftBar;
}

#pragma mark 文字 鍵盤 delegate
- (void) keyboardWillShow:(NSNotification *)notification
{
    [CoverKeyboard scrollView:self.SV_Regist textField:self.TF_ActiveField notification:notification view:self.view];
}

- (void) keyboardWillBeHidden:(NSNotification *)notification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.SV_Regist.contentInset = contentInsets;
    self.SV_Regist.scrollIndicatorInsets = contentInsets;
}

//開始編輯
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.TF_ActiveField = textField;
}

//結束編輯
- (void)textFieldDidEndEditing:(UITextField *)sender
{
    self.TF_ActiveField = nil;
}

//按下return健
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField==self.TF_PhoneNum) {
        
        [self.TF_PhoneNum resignFirstResponder];
        
        [self checkUserData];
        
    }
    
    return YES;
}

//縮下鍵盤
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    
    if (self.V_ContentView == touch.view) {
        [self.view endEditing:YES];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//返回
- (void)goBackToSourceVC:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


//選擇國碼
- (IBAction)pushCountrySelectView:(id)sender {
    CountryTableViewController *countryTVC = [self.storyboard instantiateViewControllerWithIdentifier:@"CountryTableViewController"];
    countryTVC.delegate = self;
    [self.navigationController pushViewController:countryTVC animated:YES];
}
//確認按鈕
-(IBAction)buttonPress:(UIButton *)sender{
    
    [self checkUserData];
}
-(void)checkUserData
{
    //取得Wifi mac只有12碼的16進位數字 ex: b8:f6:b1:1b:1d:17
//    self.WifiSSID = [TelephonyInfo currentWifiSSID];
    self.WifiSSID =  [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    self.WifiSSID = [self.WifiSSID stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"%@",self.WifiSSID);
    //檢查國家代碼跟wifi 是否都有
    if (self.ISO_Country_Code !=nil && self.ISO_Country_Code.length > 0 && self.WifiSSID != nil && self.WifiSSID.length > 0) {
        
        //檢查電話格式
        if ([ValidateText validatePhone:self.TF_PhoneNum.text]) {
            
            
            NSString *userPhoneNumber = [NSString stringWithFormat:@"我們將以簡訊發送驗證碼，到這個手機：%@",self.TF_PhoneNum.text];
            
            //帳號密碼都沒有問題 按了確定 觸發 delegate 事件
            [[[UIAlertView alloc]initWithTitle:@"確認手機號" message:userPhoneNumber delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確認",nil]show];
            
        }else
        {
            [WinkAlertView _showAlertViewWithTitle:@"錯誤" content:@"格式不正確" cancelButtonTitle:@"OK" showTime:3.0f];
        }
        
    }else if (self.ISO_Country_Code == nil || self.ISO_Country_Code.length == 0){
        
        [WinkAlertView _showAlertViewWithTitle:@"注意" content:@"需要選擇國家 才能註冊" cancelButtonTitle:@"確認" showTime:3.0f];
        
    }else
    {
        
        [WinkAlertView _showAlertViewWithTitle:@"注意" content:@"需要連結WIFI才能註冊" cancelButtonTitle:@"確認" showTime:3.0f];
        
    }
}


-(void)getToken
{
    afManager = [AFHTTPRequestOperationManager manager];
    
    afManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    afManager.responseSerializer.acceptableContentTypes = [afManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    
    //傳送參數 前面固定 最後一個一定要是 b8:f6:b1:1b:1d:17
    NSDictionary *parameters = @{@"type":@"token",@"secret":@"openfire",@"mac":self.WifiSSID};
    NSLog(@"%@",parameters);
    //取得token
    [afManager POST:MD_SERVER_API parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSLog(@"JSON: %@", responseObject);

        
        NSString *responseResult = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        //成功
        if ([responseResult isEqualToString:@"0"]) {
            
            self.token = responseObject[@"token"];
            
            //成功得到token 在發送帳號 過去
            [self sendRegistration];
            
        }else
        {
            [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];

            [WinkAlertView _showAlertViewWithTitle:@"失敗" content:responseObject[@"msg"] cancelButtonTitle:@"確認" showTime:3.0f];
            
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        
        [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];

        [WinkAlertView _showAlertViewWithTitle:@"失敗" content:@"網路連結失敗" cancelButtonTitle:@"確認" showTime:3.0f];


    }];

}
-(void)sendRegistration
{
    //國碼 帳號(電話) 密碼 wifi位置 還有先前取得的 token
    NSDictionary *parameters = @{@"type":@"add",@"kind":@"1",@"secret":@"openfire",@"countryCode":self.ISO_Country_Code,@"phone":self.TF_PhoneNum.text,@"password":DEFAULT_PASSWORD,@"mac":self.WifiSSID,@"token":self.token};

    //發送註冊 等待簡訊回應
    [afManager POST:MD_SERVER_API parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"JSON: %@", responseObject);
        
        NSString *responseResult = [NSString stringWithFormat:@"%@",responseObject[@"result"]];

        //成功
        if ([responseResult isEqualToString:@"0"]) {
            
            //loading 結束
            [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:YES];
            
            //跳到簡訊輸入頁面
   
            [self toSMSViewController];
            
        }else if ([responseResult isEqualToString:@"3"])
        {
            [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];
            
            //已經註冊過 跳到已註冊過的畫面上
            UserAlreadyExistViewController *userAlreadyExistVC = [self.storyboard instantiateViewControllerWithIdentifier:@"UserAlreadyExistViewController"];
            userAlreadyExistVC.token=self.token;
            userAlreadyExistVC.WifiSSID=self.WifiSSID;
            userAlreadyExistVC.ISO_Country_Code=self.ISO_Country_Code;
            userAlreadyExistVC.userPhoneNumber=self.TF_PhoneNum.text;
            [self.navigationController pushViewController:userAlreadyExistVC animated:YES];
            
            

        }else if([responseResult isEqualToString:@"4"])
        {
            //帳號已經註冊 但是未成功認證
            [self resendSMS];
            
        }else
        {
            
            [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];

        }
        /*
         CODE_IllegalArgument = 1;
         CODE_TokenTimeOut = 2;
         CODE_UserAlreadyExists = 3;
         CODE_UserAlreadyExistsNotEnable = 4;
         CODE_UserNotFound = 6;
         */
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        
        [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];

        [WinkAlertView _showAlertViewWithTitle:@"失敗" content:@"網路連結失敗" cancelButtonTitle:@"確認" showTime:3.0f];
        

    }];
}


//這裏算是重複寫同一個功能了 有時間要修改
-(void)resendSMS
{
    NSDictionary *parameters = @{@"type":@"sms",@"kind":@"1",@"secret":@"openfire",@"countryCode":self.ISO_Country_Code,@"phone":self.TF_PhoneNum.text,@"token":self.token};

    //發送註冊 等待簡訊回應
    [afManager POST:MD_SERVER_API parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"JSON: %@", responseObject);
        
        NSString *responseResult = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        //成功
        if ([responseResult isEqualToString:@"0"]) {
            
            [self.AV_LoadingAlertView dismissWithClickedButtonIndex:0 animated:NO];

            //跳到簡訊頁面
            [self toSMSViewController];

        }else
        {
            [WinkAlertView _showAlertViewWithTitle:@"簡訊重新發送失敗" content:responseObject[@"msg"] cancelButtonTitle:@"確認" showTime:3.0f];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        
        [WinkAlertView _showAlertViewWithTitle:@"失敗" content:@"網路連結失敗" cancelButtonTitle:@"確認" showTime:3.0f];
        
        
    }];

}
-(void)toSMSViewController
{
    SMSViewController *SMSVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SMSViewController"];
    SMSVC.token=self.token;
    SMSVC.WifiSSID=self.WifiSSID;
    SMSVC.ISO_Country_Code=self.ISO_Country_Code;
    SMSVC.userPhoneNumber=self.TF_PhoneNum.text;
    
    [self.navigationController pushViewController:SMSVC animated:YES];
}

#pragma mark CountryTableViewControllerDelegate
-(void)selectCountry:(NSDictionary *)countryDict
{
    //選擇完畢後 將國家名稱填上去
    self.LB_CountryCode.text = countryDict[@"country"];
    //選擇完畢後，將國家代碼 帶給 ISO_Country_Code
    self.ISO_Country_Code = countryDict[@"code"];
    
    [[NSUserDefaults standardUserDefaults]setValue:countryDict[@"country"] forKey:@"country"];
    
    [[NSUserDefaults standardUserDefaults]setValue:countryDict[@"code"] forKey:@"code"];
    
    
}

#pragma mark AlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   
        if (buttonIndex==1) {
            
            //並且把等待的 alertView show 出來
            self.AV_LoadingAlertView = [[UIAlertView alloc]initWithTitle:@"註冊中" message:@"請等待..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [self.AV_LoadingAlertView show];
            
            //先取得 token
            [self getToken];
        }
    
}

/*
 
 APIs
 
 The general API address is http://xmpp.mooredoll.com:9090/plugins/mooredoll/mooredollservice?
 The following services use the same address.
 Each response includes a result, value 0 means requesting successfully; value 1, 2, and above are error occurred. (Example: {"result":3,"msg":"phone registered"})
 
 一般的API網址 http://xmpp.mooredoll.com:9090/plugins/mooredoll/mooredollservice?
 以下服務使用以上的網址
 每個響應包括一個結果，數值0表示請求成功;值1，2，和更多都是錯誤的連線
 
 
 Registration (general account) 註冊一般會員
 
 getToken  取得toKen
 POST parameters: POST 參數
 type = "token"
 secret = "openfire"
 mac = the device identifier (Mac of device, in general case is WiFi Mac) example: "AABBCCDDEEFF"  應該是說要傳device token
 RESPONSE JSON string: 回傳的json
 {"result":0,"token":"d00ac8c627e735570ffd705133dc0eb89d5c5c5d36e84a268d995dfc9b5315c2bb229e8d7812aed404474d2611ecc6b00a81139428d5e59f8b3179c3cc609a93"}
 
 
 sendRegistration 發送註冊  註冊頁面的註冊
 POST parameters:
 type = "add"
 kind = "1"
 secret = "openfire"
 countryCode = get SIM card country ISO. example: "886" 發送sim 卡國碼
 phone = from account field "0912345678"  電話
 password = from password field   密碼
 mac = from WiFi Mac
 token = from getToken API response   拿到的Token
 RESPONSE JSON string
 {"result":0,"msg":"ok"}
 
 sendPasscode
 POST parameters:
 type = "enable"
 secret = "openfire"
 countryCode = the same as sendRegistration 發送sim 卡國碼
 phone = the same as sendRegistration 電話
 sms = from SMS  簡訊
 RESPONSE JSON string:
 {"result":0,"msg":"ok"}
 
 resendSMS 再次發送sms
 POST parameters:
 type = "sms"
 kind = "1"
 secret = "openfire"
 countryCode = the same as registration data 發送sim 卡國碼
 phone = the same as registration data 電話
 token = the same as registration data 拿到的Token
 RESPONSE JSON string:
 {"result":0,"msg":"ok"}
 
 Activation (Doll’s account)
 
 getTuid 取得 TU ID
 POST parameters:
 category = "1"
 type = "add"
 secret = "openfire"
 username = user’s account (example: "886.912345678") 使用者帳號
 password = user’s password 使用者密碼
 RESPONSE JSON string:
 {"result":0,"tuid":"d00ac8c627e735570ffd705133dc0eb89d5c5c5d36e84a268d995dfc9b5315c2bb229e8d7812aed404474d2611ecc6b00a81139428d5e59f8b3179c3cc609a93"}
 
 Password change 變更密碼
 
 changePassword
 POST parameters:
 type = "changepwd"
 secret = "openfire"
 username = user’s account (example: "886.912345678") 使用者帳號
 oldpwd = from old password field 舊密碼
 newpwd = from new password field 新密碼
 RESPONSE JSON string:
 {"result":0,"msg":"ok"}
 
 Search friend 搜尋朋友
 
 searchFriends
 POST parameters:
 type = "search"
 secret = "openfire"
 phones = "886.916123456,886.989123456,123456689212"  電話
 RESPONSE JSON string:
 No Mooredoll’s account: {"result":0,"user":[]"} 不存在
 Mooredoll’s account exist: {"result":0,"user":[{"phone":886.916123456","jid":"ce01394592464dc88860"}, {"phone":123456689212","jid":"7366f6038d7742ea9906"}]"} 存在
 
 Add friend 新增好友
 
 addFriend
 type = "add_friend"
 secret = "openfire"
 username = user’s account (example: "886.912345678") 使用者帳號
 friend = "friend’s jid" 朋友的jid
 RESPONSE JSON string:
 {"result":0,"msg":"ok"}
 
 Error code definition
 TBD
 
 
 */

@end
